package com.yazi.mxz.common.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.myframework.smhj.common.exception.MyEntityNotExistsException;
import com.myframework.smhj.common.exception.MyException;
import com.myframework.smhj.common.tool.DateUtil;
import com.myframework.smhj.hibernate.dao.BasicService;
import com.myframework.smhj.hibernate.dao.Dao;
import com.yazi.mxz.common.db.dao.CookDao;
import com.yazi.mxz.common.db.dao.MaterialDao;
import com.yazi.mxz.common.entity.ValueFactory;
import com.yazi.mxz.common.entity.beans.Cook;
import com.yazi.mxz.common.entity.beans.Material;
import com.yazi.mxz.common.service.CookService;

@Service("cookService")
public class CookServiceImpl extends BasicService<Cook> implements CookService {
	private static Logger log = LoggerFactory.getLogger(CookServiceImpl.class);

	@Resource
	CookDao cookDao;
	@Resource
	MaterialDao materialDao;
	
	@Override
	protected Dao<Cook> getDao() {
		return cookDao;
	}
	
	@Override
	public Cook addOrEdit(Cook cook, List<Material> materials) throws MyException {
		Long cookId = cook.getCookId();
		Cook destCook = null;
		if (null != cookId && cookId > 0) {
			log.debug("addOrEdit->modify：cookId={}", cookId);
			
			// 删除菜谱中原有的食材
			materialDao.deleteByCookId(cookId);
			
			destCook = cookDao.get(cookId);
			if (null == destCook) {
				throw new MyEntityNotExistsException();
			}
			
			ValueFactory.combine(cook, destCook);
			destCook = cookDao.merge(destCook);
			
		} else {
			log.debug("addOrEdit->add：name={}", cook.getName());
			
			cook = ValueFactory.validate(cook);
			cook.setAddTime(DateUtil.getTimeStamp());
			cook.setCookId(null);
			destCook = cookDao.persist(cook);
		}
		
		// 添加食材
		for(Material material : materials){
			material.setCook(destCook);
			materialDao.persist(material);
		}
		
		return destCook;
	}

	@Override
	public void remove(long cookId) {
		log.debug("remove: cookId={}", cookId);
		
		Cook cook = cookDao.get(cookId);
		
		if (null != cook) {
			
			// 删除该菜谱下的食材
			materialDao.deleteByCookId(cookId);
			
			cookDao.delete(cook);
		}
	}

}
